package cn.wolfcode.wolf2w.Interceptor;

import cn.wolfcode.wolf2w.annotation.RequiredLogin;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.logging.Handler;

@Component
public class CheckLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//解决拦截器跨域问题
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //判段映射方法有没有自定义注解
        HandlerMethod hm = (HandlerMethod) handler;
        String token = request.getHeader("token");
        UserInfo user = userInfoRedisService.getUserInfoByToken(token);
        //user==null就说明没登陆，返回没有登录结果提示
        if (hm.hasMethodAnnotation(RequiredLogin.class)) {
            //如果有 再登陆检查
            if (user == null) {
                response.setContentType("application/json; charset=utf-8");
                response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
                return false;//不放行
            }
        }

        return true;
    }

}
